package cn.javaweb.library;

import cn.javaweb.entity.User;
import cn.javaweb.group0.model.LogModel;
import cn.javaweb.group0.model.RoleModel;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebFilter(urlPatterns = "/*")
public class Filter implements javax.servlet.Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        HttpServletRequest  req  = (HttpServletRequest) servletRequest;

        //解决中文乱码
        req.setCharacterEncoding("utf8");
        resp.setCharacterEncoding("utf8");
        resp.setContentType("application/json;charset=utf-8");

        //允许跨域请求
        resp.setHeader("Access-Control-Allow-Headers", "*");
        //允许所有的域
        resp.setHeader("Access-Control-Allow-Origin","*");

        //解决未登录访问拦截问题
        String requestURI = req.getRequestURI();


        if(requestURI.equals("/api/user/login") || requestURI.equals("/api/common/init")){
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            //用户身份验证
            String token = req.getHeader("token");
            User user = Token.checkToken(token);
            if(user==null){
                AjaxResult r = AjaxResult.error("请登录");
                r.put("code", 401);
                resp.getWriter().print(r);
            }else{
                req.setAttribute("user", user);
                LogModel logModel = new LogModel();
                logModel.addLog(req.getRemoteHost(), req.getRequestURI(), req.getMethod(),"",user.getUsername());


                RoleModel roleModel = new RoleModel();

                List<String> rolelist = roleModel.getRolesByUser(user);

                //访问控制
                if(requestURI.equals("/api/student/course")){
                    //查询学生今天的课程 - 需要学生角色
                    if(rolelist.indexOf("学生")<0){
                        resp.getWriter().print(
                            AjaxResult.error("无操作权限")
                        );
                        return;
                    }
                }

                filterChain.doFilter(servletRequest, servletResponse);
            }

        }

    }

    @Override
    public void destroy() {

    }
}
